/***
 *   创建订单相应接口
 *   Created by lihao on 2018-04-13
 */

let express = require('express');
let router = express.Router();
let db = require('../conf');
let tools = require('../util');

//新建订单
router.post('/create',function(req,res){

    let bodyTemp = req.body;
    let endSql = {},c_s={},f_s={};
    let r_b_c = req.body.customerInfo;
    let r_b_f = req.body.freightInfo;

    let sql_obj = [
        {name: 'order', tableName: 'by_order', cols:["orderId","destination", "customer_id", "deliverGoodsTime", "freight_id",
                "orderType", "deposit", "totalMoney", "payWay", "payStatus"],num:10},
        {name: 'chairInfo', tableName:'by_order_chair',cols: ["orderId","type","color","number","unit","board"],num:6},
        {name: 'tableInfo', tableName:'by_order_table',cols: ["orderId","type","number","size","color","material","footer","footerMaterial","desktop"],num:9},
        {name: 'teaTableInfo', tableName:'by_order_tea',cols: ["orderId","type","number","size","color","desktop"],num:6},
        {name: 'tvTableInfo', tableName:'by_order_tv',cols: ["orderId","type","number","size","color","desktop"],num:6},
        {name: 'remarkInfo', tableName:'by_order_remark',cols: ["orderId","remark"],num:2}
    ];

    // 判断货运部或用户是否是手输进来  1.手输进行数据库保存   2 系统选择 将相应的id 传到后台即可
    try{
       if (req.body.customerInfo.id) {
           // 数据源于数据库
           bodyTemp.customer_id = r_b_c.id;
           delete req.body.customerInfo

       }  else {
           // 手工录入数据
           c_s = {
               sql: 'INSERT INTO by_bbd_customer (value,phone,p_c_a,street) VALUES '+ tools.into_params_num(1,4),
               value: [r_b_c.value, r_b_c.phone, r_b_c.p_c_a, r_b_c.street]
           }
       }

        if (req.body.freightInfo.id) {
            // 数据源于数据库
            bodyTemp.freight_id = r_b_f.id;
            delete req.body.freightInfo

       }  else {
            // 手工录入数据
            f_s = {
                sql: 'INSERT INTO by_bbd_customer (value,phone,address) VALUES '+ tools.into_params_num(1,3),
                value: [r_b_f.value, r_b_f.phone, r_b_f.address]
            }

        }

        // 获取系统订单号
        let sql_total = 'SELECT count(*) as total FROM  by_order';

        db(sql_total,[]).then(data =>{

            let sysId = tools.createSysId(data[0].total+1).sysId;

            for(let n=0; n< sql_obj.length;n++){

                let _b = sql_obj[n];
                let bT = n===0?tools.get_order(bodyTemp):bodyTemp[_b.name];

                // 如果有数据，才进行sql 插入
                if(bT.length !== 0){
                    endSql[n] = {
                        sql: 'INSERT INTO '+ _b.tableName +' ('+_b.cols+') VALUES '+ tools.into_params_num(bT.length,_b.num),
                        value: tools.format_data_imp_2(bT, _b.cols, sysId)
                    };
                }

            }

            c_s.value?endSql.c_s = c_s:'';
            f_s.value?endSql.f_s = f_s:'';

            let _z = tools.obj2sql(endSql);

            db(_z.sql, _z.data).then(data=>{

                res.send({
                    success: false,
                    message: '保存订单成功',
                    code: 0,
                    data: {}

                })
            }).catch(err=>{

                res.send({
                    success: false,
                    message: err,
                    code: '10003',
                    data: {},
                    all_sql: _z

                })
            });


        })


    } catch (e){
        res.send({
            code:10003,
            success: false,
            message: e
        })
    }

});

//创建订单时，客户，从后台拿取用户信息
router.get('/customer',function(req,res){

    const name = '%'+req.query.customer+'%';
    const sql = 'SELECT id,value,phone,p_c_a,street FROM by_bbd_customer WHERE value like ? ';

    db(sql,[name]).then(data=>{

        res.send({
            success: true,
            message: '获取用户名称成功',
            code: 0,
            data: data
        })
    }).catch(err=>{
        res.send({
            success: false,
            message: err,
            code: '10003',
            data: []
        })
    })
})

//获取货运部信息
router.get('/freight',function(req,res){

    const name = '%'+req.query.freight+'%';
    const sql = 'SELECT * FROM by_bbd_freight WHERE value like ?';

    db(sql,[name]).then(data=>{

        res.send({
            success: true,
            message: '获取货运部成功',
            code: 0,
            data: data
        })
    }).catch(err=>{
        res.send({
            success: false,
            message: err,
            code: '10003',
            data: []
        })
    })
})

module.exports = router;